﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;

namespace WLMes
{
    public class JsonRef
    {
        /// <summary>
        /// 序列化
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static string ObjectToJson(object obj)
        {
            return JsonConvert.SerializeObject(obj, Newtonsoft.Json.Formatting.Indented);
        }
        /// <summary>
        /// 反序列化json对象
        /// </summary>
        /// <param name="txtJson">转换成json对象</param>
        /// <returns></returns>
        public static JObject JObjectData(string txtJson)
        {
            JObject ja = (JObject)JsonConvert.DeserializeObject(txtJson);
            return ja;
        }
        /// <summary>
        /// 反序列JSON集合
        /// </summary>
        /// <param name="txtJson">转换成json对象</param>
        /// <returns></returns>
        public static JArray JArrayData(JToken jto)
        {
            string txtJson = Convert.ToString(jto);
            JArray ja = (JArray)JsonConvert.DeserializeObject(txtJson);
            return ja;
        }
        /// <summary>
        /// 获取json对象元素
        /// </summary>
        /// <param name="ja">json对象</param>
        /// <param name="Emun">属性名</param>
        /// <returns></returns>
        public static string JObjectStr(JObject ja, string Emun)
        {
            return Convert.ToString(ja[Emun]);
        }
        /// <summary>
        /// 获取json集合元素
        /// </summary>
        /// <param name="ja">json集合</param>
        /// <param name="Emun">属性名</param>
        /// <param name="index">集合index</param>
        /// <returns></returns>
        public static string JArrayStr(JArray ja, string Emun, int index)
        {
            return Convert.ToString(ja[index][Emun]);
        }
        /// <summary>
        /// 获取单元值
        /// </summary>
        /// <param name="jObject">json对象</param>
        /// <param name="serial">index集合，-1表示不是集合</param>
        /// <param name="columname">列名</param>
        /// <returns></returns>
        public static string JsonCell(JObject jObject, List<int> serial, List<string> columname)
        {
            string str = "";
            var objm = jObject;
            int index = 0;
            foreach (int ser in serial)
            {
                if (ser == -1)
                {
                    JObject obj = (JObject)objm;
                    str = Convert.ToString(obj[columname[index]]);
                    objm = obj;
                }
                else
                {
                    JArray arr = (JArray)JsonConvert.DeserializeObject(str);
                    str = Convert.ToString(arr[ser][columname[index]]);
                }
                index++;
            }
            return str;
        }
    }
}
